var http = require('http'),
    q = require('querystring');

exports.index = function () {
    var _t = this;
    PostSBO('/GenerateVC.aspx', {fromPage:'default'},
        function (data) {
            data = data.toString().match(/\(.+\)/);
            var content = eval('new Array' + data);
            GetSBO('/' + content[0],
                function (data) {
                    var buf = new Buffer(data);
                    console.log(buf.length);
                    _t.renderImg(buf);
                });
        }
    );
};

function GetSBO(url, OnDataRecv) {
    ReqSBO(url, 'GET', OnDataRecv);
}

function PostSBO(url, form, OnDataRecv) {
    ReqSBO(url, 'POST', OnDataRecv, form);
}

function ReqSBO(url, method, OnDataRecv, form) {
    var _t = this;

    var headers = {
        'Content-Type':'application/x-www-form-urlencoded',
        'User-Agent':'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0',
        'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Language':'en-us,en;q=0.5'
    };

    if (form) {
        var buff = new Buffer(q.stringify(form));
        headers['Content-Length'] = buff.length;
    }
    var request = http.request(
        {
            method:method,
            host:'sports.sbobetasia.com',
            port:80,
            path:url,
            headers:headers
        },
        function (res) {
            res.on('data', function (chunk) {
                OnDataRecv(chunk);
            });
        }
    ).on('error', function (e) {
            console.log(e);
        });
    if (form) {
        request.write(buff);
    }
    request.end();
}